<template>
  <div class="dialog-content">
    <el-row :gutter="40">
      <!-- 左侧日历区域 -->
      <el-col :span="14">
        <div class="calendar-section">
          <el-calendar v-model="form.visitDate" :day-cell-class-name="getDayCellClassName">
            <template #date-cell="{ data }">
              <div class="custom-cell" @click="openAppointmentDialog(data.day)">
                <!-- 默认日期显示 -->
                {{ data.day.split('-').slice(2).join('-') }}

                <!-- 日期标记 -->
                <div v-if="isDateMarked(data.day)" class="date-marker">
                  <!-- 圆点标记 -->
                  <div class="dot"></div>

                  <!-- 或者使用图标 -->
                  <!-- <el-icon class="icon"><star /></el-icon> -->
                </div>
              </div>
            </template>
          </el-calendar>
          <div class="stats">
            <div class="stat-item">
              <span class="label">已预约患者人数</span>
              <span class="value">{{ plansPage.total }}</span>
            </div>
            <div class="stat-item">
              <span class="label">已预约当日患者人数</span>
              <span class="value">{{ currentNumber }}</span>
            </div>
          </div>
        </div>
      </el-col>

      <!-- 右侧通知设置 -->
      <el-col :span="10">
        <el-form label-width="100px" label-position="top">
          <el-form-item label="是否通知：">
            <el-radio-group v-model="form.notice" @change="handleNoticeChange">
              <el-radio :label="true" value="1">是</el-radio>
              <el-radio :label="false" value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

<!--          <el-form-item label="选择通知方式：">
            <el-checkbox-group v-model="form.noticeType" :disabled="form.notice == '0'">
              >
              <el-checkbox label="短信" value="1" />
              <el-checkbox label="邮件" value="2" />
            </el-checkbox-group>
          </el-form-item>-->

          <el-form-item label="选择通知时间：">
            <el-select v-model="form.noticeTime" multiple :disabled="form.notice == '0'">
              <el-option
                v-for="item in notifyTimeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-date-picker
              v-if="form.noticeTime === 'custom'"
              v-model="form.customTime"
              type="datetime"
              placeholder="选择自定义时间"
              class="custom-time-picker"
            />
          </el-form-item>

          <el-form-item label="通知内容：">
            <el-input
              v-model="form.noticeContent"
              :disabled="form.notice == '0'"
              type="textarea"
              :rows="4"
              placeholder="请在此处编辑通知的内容"
            />
          </el-form-item>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">{{
              menuVal.type === 1 ? '修改预约' : '添加预约'
            }}</el-button>
          </div>
        </el-form>
      </el-col>
    </el-row>
    <!-- 预约记录表格 -->
    <div class="appointment-records">
      <h3>预约记录</h3>
      <el-table :data="tableData" empty-text="没有找到匹配的记录">
        <el-table-column prop="visitDate" label="随访时间" />
        <el-table-column prop="notice" label="是否通知">
          <template #default="scope">
            <span>{{ ['否', '是'][Number(scope.row.notice)] }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column prop="noticeType" label="通知方式">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.noticeType.split(',')" :key="index"
              >{{ ['短信', '邮件'][Number(item) - 1] }}
              <span v-if="index + 1 != scope.row.noticeType.split(',').length">|</span>
            </span>
          </template>
        </el-table-column>-->
        <el-table-column prop="noticeTime" label="通知时间">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.noticeTime.split(',')" :key="index"
              >{{ ['提前一周通知', '提前三天通知', '当天通知'][Number(item) - 1] }}
              <span v-if="index + 1 != scope.row.noticeTime.split(',').length">|</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="noticeContent" label="通知内容" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            {{ ['已预约', '已发送'][Number(scope.row.status) - 1] }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" @click="handleMenu(1, scope.row, scope.$index)">修 改</el-button>
            <el-button type="text" @click="handleMenu(2, scope.row, scope.$index)">取 消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="plansPage.current"
          v-model:page-size="plansPage.pageSize"
          :size="size"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="plansPage.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { dictionary } from '@/api/crf/crf';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getList, getDetail, add, update, remove,getNoticeContent } from '@/api/visitplanrecord/visitPlanRecord';
import { ref, reactive, onMounted } from 'vue';

import { useRoute } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore();
const route = useRoute();
const routerQuery = ref({});
routerQuery.value = route.query;

const visible = ref(true);
const appointmentType = ref('单次预约');

const form = ref({
  notice: '0',
  noticeType: [],
  noticeTime: [],
  customTime: '',
  noticeContent: '',
  visitDate: new Date(),
});

let plansPage = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

const props = defineProps({
  appointmentData: {
    type: Object,
    default: {},
  }
});

let tableData = ref([]);

const notifyTimeOptions = ref([]);

let menuVal = ref({
  type: null,
  row: {},
  index: null,
});
/*
  type 1:修改
  type 2:取消
*/
const handleMenu = (type, row = {}, index = null) => {
  let val = JSON.parse(JSON.stringify(row));
  menuVal.value.type = type;
  menuVal.value.row = row;
  menuVal.value.index = index;
  if (type === 1) {
    val.noticeTime = val.noticeTime.split(',');
    val.noticeType = val.noticeType.split(',');
    form.value = val;
  }
  if (type === 2) {
    ElMessageBox.confirm(`确认取消${row.visitDate}随访吗`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        return remove(row.id);
      })
      .then(() => {
        initTableData(plansPage.value);
        ElMessage.success('操作成功!');
      });
  }
};
const handleNoticeChange = () => {
  form.value.noticeType = [];
  form.value.noticeTime = [];
  form.value.noticeContent = '';
  if(form.value.notice == '1') {
    getNoticeContent(formatDate(form.value.visitDate), null).then(res => {
      form.value.noticeContent = res.data.data;
    });
  }
};
const handleSubmit = () => {
  if (isBeforeToday(form.value.visitDate)) {
    ElMessage.error('请选择正确的日期');
    return;
  }


  /*if (form.value.notice == '1' && form.value.noticeType.length == 0) {
    ElMessage.error('请选择通知方式');
    return;
  }*/

  if (form.value.notice == '1' && form.value.noticeTime == 0) {
    ElMessage.error('请选择通知时间');
    return;
  }

  if (form.value.notice == '1' && form.value.noticeContent == '') {
    ElMessage.error('请选择通知内容');
    return;
  }


  if (form.value.noticeType instanceof Array) {
    form.value.noticeType = form.value.noticeType.join(',');
  }
  if (form.value.noticeTime instanceof Array) {
    form.value.noticeTime = form.value.noticeTime.join(',');
  }
  form.value.visitDate = formatDate(form.value.visitDate);
  form.value.caseUserId = sendVal.value.id;
  form.value.trial = routerQuery.value.trialId;
  // delete form.value.checkbox;
  add(form.value).then(res => {
    ElMessage({
      type: 'success',
      message: '操作成功!',
    });
    form.value.noticeType = [];
    form.value.noticeTime = [];
    form.value.notice = '0';
    form.value.noticeContent = '';
    // for (const key in form.value) {
    //   form.value[key] = '';
    //   if (form.value.noticeType) {
    //     form.value.noticeType = [];
    //   }
    //   if (form.value.noticeTime) {
    //     form.value.noticeTime = [];
    //   }
    //   form.value.notice = '0';
    // }
    initTableData(plansPage.value);
  });
};



const handleCurrentChange  = currentPage => {
  plansPage.value.currentPage = currentPage;
  initTableData(plansPage.value);
};
const handleSizeChange = pageSize => {
  plansPage.value.pageSize = pageSize;
  initTableData(plansPage.value);
};


// 判断是否是当天之前日期
const isBeforeToday = date => {
  // 将传入的日期转换为 Date 对象
  const inputDate = new Date(date);

  // 获取今天的日期，设置时间为00:00:00，以确保只比较日期部分
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  // 比较传入日期与今天的日期
  return inputDate < today;
};

// 创建日期Set用于快速查找
const markedDates = computed(() => {
  return new Set(tableData.value.map(item => item.visitDate));
});

// 检查当前日期是否需要标记
const isDateMarked = dateString => {
  return markedDates.value.has(dateString);
};
let currentNumber = ref(0);
const openAppointmentDialog = day => {

  currentNumber.value = tableData.value.filter(item => item.visitDate === day).length;
  if(form.value.notice == '1') {
    getNoticeContent(day, null).then(res => {
      form.value.noticeContent = res.data.data;
    });
  }
};

const formatDate = date => {
  let d = new Date(date);
  let year = d.getFullYear();
  let month = String(d.getMonth() + 1).padStart(2, '0');
  let day = String(d.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
};

// 表格接口
const initTableData = (page, params = {}) => {
  let values = {
    descs: 'create_time',
    ...params,
    caseUserId: sendVal.value.id,
    trial:routerQuery.value.trialId,
  };
  getList(page.current, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    plansPage.value.total = DATA.total;
    tableData.value = DATA.records;
    openAppointmentDialog(getTodayDate());
  });
};
let statusList = ref([]);
const initData = () => {
  notifyTimeOptions.value = [];
  statusList.value = [];
  dictionary('follow_notice_time').then(res => {
    res.data.data.forEach(item => {
      notifyTimeOptions.value.push({
        label: item.dictValue,
        value: item.dictKey,
      });
    });
  });
  dictionary('visit_plan_record_status').then(res => {
    res.data.data.forEach(item => {
      statusList.value.push({
        label: item.dictValue,
        value: item.dictKey,
      });
    });
  });
};
const getTodayDate = () => {
  const today = new Date();
  const year = today.getFullYear();
  let month = today.getMonth() + 1;
  let day = today.getDate();
  month = month < 10 ? '0' + month : month; // 手动补零[1,5,6](@ref)
  day = day < 10 ? '0' + day : day;
  return `${year}-${month}-${day}`;
};

const getTodayDateYmd = () => {
  const today = new Date();
  const year = today.getFullYear();
  let month = today.getMonth() + 1;
  let day = today.getDate();
  month = month < 10 ? '0' + month : month; // 手动补零[1,5,6](@ref)
  day = day < 10 ? '0' + day : day;
  return `${year}年${month}月${day}日`;
};

let sendVal = ref({})
const opens = (row) => {
  sendVal.value = row;
  initTableData(plansPage.value);
}
defineExpose({
  opens,
});
onMounted(() => {
  initData();
  sendVal.value = props.appointmentData;
  initTableData(plansPage.value);
});
</script>

<style scoped lang="scss">
.appointment-dialog {
  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .calendar-title {
      font-size: 16px;
      color: #333;
    }
  }
  .dialog-content {
    padding: 20px;

    .calendar-section {
      .custom-calendar {
        .calendar-week-header {
          display: grid;
          grid-template-columns: repeat(7, 1fr);
          text-align: center;
          color: #666;
          margin-bottom: 10px;
        }

        .calendar-days {
          display: grid;
          grid-template-columns: repeat(7, 1fr);
          gap: 5px;

          .day-cell {
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
            cursor: pointer;

            &.selected {
              background: #409eff;
              color: white;
            }
          }
        }
      }

      .stats {
        margin-top: 20px;
        display: flex;
        gap: 30px;
        padding: 15px;
        border: 1px solid #ebeef5;
        border-radius: 4px;

        .stat-item {
          .label {
            color: #666;
            margin-right: 10px;
          }
          .value {
            color: #409eff;
            font-weight: bold;
          }
        }
      }
    }

    .appointment-records {
      margin-top: 30px;

      h3 {
        color: #333;
        margin-bottom: 15px;
      }

      .pagination {
        margin-top: 15px;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        .record-info {
          color: #666;
          font-size: 12px;
        }
      }
    }

    .dialog-footer {
      margin-top: 20px;
      text-align: right;
    }
  }
}
/* 修改弹窗内容区高度 */
:deep(.el-dialog__body) {
  height: 80vh;
  overflow-y: auto; /* 添加滚动条 */
}
:deep(.el-form) {
  .el-form-item__label {
    font-weight: normal;
    color: #333;
  }
}

.custom-time-picker {
  margin-top: 10px;
  width: 100%;
}

.custom-cell {
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.date-marker {
  position: absolute;
  bottom: 5px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
}

/* 圆点样式 */
.dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #f56c6c; /* 红色圆点 */
}

/* 图标样式 */
.icon {
  color: #67c23a; /* 绿色图标 */
  font-size: 14px;
}
</style>
